//
//  YATaskGameListHandler.m
//  YoucApi
//
//  Created by Liam on 11/25/12.
//
//

#import "YATaskGameListHandler.h"
#import "YAObjGame.h"

#ifndef SAFE_STRING
#define SAFE_STRING(p) \
{\
	if (p == nil) {\
		p = @"";\
	}\
}
#endif

@interface YATaskGameListHandler()

@property (nonatomic, retain) YoucApiTask *task;

@end

@implementation YATaskGameListHandler

@synthesize task = _task;

- (id)initWithTask:(YoucApiTask *)task
{
	if (self = [super init])
	{
		self.task = task;
	}
	
	return self;
}

- (void)dealloc
{
	SAFE_RELEASE(_task);
	[super dealloc];
}

- (YARespGameList *)gameListWithResponse:(id)responseObject withError:(NSError *)error
{
	YARespGameList *respGameList = [[[YARespGameList alloc] initWithError:error context:self.task.context] autorelease];
	
    NSMutableArray *list = nil;
	
	if ([error code] == YoucApiErrorSuccess)
	{
		list = [NSMutableArray array];
		
		NSArray *jsonList = (NSArray *)responseObject;
		for (NSDictionary *item in jsonList)
		{
			YAObjGame *game = [[[YAObjGame alloc] init] autorelease];
			game.gameId = SAFE_STRING([item objectForKey:KEY_ID]);
			game.gameName = SAFE_STRING([item objectForKey:KEY_NAME]);
			game.gameType = SAFE_STRING([item objectForKey:KEY_TYPE]);
			game.gameImage = SAFE_STRING([item objectForKey:KEY_IMAGE]);
            game.gameTodayNum = [SAFE_STRING([item objectForKey:KEY_TODAYNUM]) intValue];
			game.isAttention = [SAFE_STRING([item objectForKey:KEY_ISATTENTION]) boolValue];
			[list addObject:game];
		}
	}
	
	respGameList.list = list;
	
	return respGameList;
}

- (void)dealWithJSONResponse:(id)responseObject withError:(NSError *)error
{
	YARespGameList *respGameList = [self gameListWithResponse:responseObject withError:error];
	
	if ([self.task.delegate respondsToSelector:@selector(getGameListResponse:respGameList:)])
	{
		[self.task.delegate getGameListResponse:self respGameList:respGameList];
	}
}

@end
